package cn.cytong.nk0713.listener;

import cn.cytong.rpc.server.RpcServer;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.json.JsonLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;

/**
 * rpc启动
 */
public class LauncherAppListener implements ServletContextListener {

    private Logger logger = LoggerFactory.getLogger(LauncherAppListener.class);
    private RpcServer server;
    private Ioc ioc;

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            String dir = servletContextEvent.getServletContext().getRealPath("/");
            File configFile = new File(dir + File.separator + "config.js");
            ioc = new NutIoc(new JsonLoader(configFile.getPath()));

            server = ioc.get(RpcServer.class, "rpcServer");

            server.start();
        } catch (Exception e) {
            logger.error("error in class LauncherAppListener", e);
        }
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        server.stop();
        if (ioc != null) {
            ioc.depose();
        }
    }
}
